import java.util.ArrayDeque;
import java.util.Queue;

/**
 * 226. 翻转二叉树
 */
public class Solution_226 {
    /**
     * 方法二：递归（深度优先遍历）
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        root.left = right;
        root.right = left;
        return root;
    }

    /**
     * 方法一：广度优先遍历
     */
    public TreeNode invertTree1(TreeNode root) {
        if (root == null) {
            return null;
        }

        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            // 每次都从队列中拿一个节点，并交换这个节点的左右子树
            TreeNode cur = queue.poll();
            TreeNode left = cur.left;
            cur.left = cur.right;
            cur.right = left;
            // 如果当前节点的左子树不为空，则放入队列等待后续处理
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            // 如果当前节点的右子树不为空，则放入队列等待后续处理
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
        return root;
    }

    public static void main(String[] args) {
        Solution_226 solution = new Solution_226();
        TreeNode root = new TreeNode(4);
        TreeNode left = new TreeNode(2, new TreeNode(1), new TreeNode(3));
        TreeNode right = new TreeNode(7, new TreeNode(6), new TreeNode(9));
        root.left = left;
        root.right = right;
        solution.invertTree(root);
    }
}
